package com.hsxshop.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hsxshop.util.JsonTool;
import lombok.extern.java.Log;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by wangchongya on 17/7/5.
 */
@RestController
@RequestMapping(value = "/File/")
@Log
public class FileUploadController {

    @RequestMapping(value = "uploadFile", method = RequestMethod.POST,produces= MediaType.APPLICATION_JSON_UTF8_VALUE,consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    public String uploadPic(@RequestParam("file") MultipartFile file){


        // 获取图片的文件名
        String fileName = file.getOriginalFilename();
        // 获取图片的扩展名
        String extensionName = fileName
                .substring(fileName.lastIndexOf(".") + 1);
        // 新的图片文件名 = 获取时间戳+"."图片扩展名
        String newFileName = String.valueOf(System.currentTimeMillis())
                + "." + extensionName;

        String fileDir= new SimpleDateFormat("yyyy-MM-dd").format(new Date());

        File tempFile = new File(System.getProperty("hsx.webappRoot")+"html/upload/"+fileDir, newFileName);
        if (!tempFile.getParentFile().exists()) {
            tempFile.getParentFile().mkdirs();
        }
        if (!tempFile.exists()) {
            try {
                tempFile.createNewFile();
            }catch (IOException ex){
             return   JsonTool.returnObjectJsonError(null);
            }

        }
        try{
            file.transferTo(tempFile);
        }catch (IOException ex){
            return   JsonTool.returnObjectJsonError(null);
        }

        Map map=new HashMap();
        map.put("url","html/upload/"+fileDir+"/"+newFileName);
        map.put("tmpUrl",fileDir+"/"+newFileName);
        return JsonTool.returnObjectJsonSuccess(map);
    }

    @RequestMapping(value = "uploadKingPic", method = RequestMethod.POST,produces= MediaType.APPLICATION_JSON_UTF8_VALUE,consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    public String uploadKPic(@RequestParam("imgFile") MultipartFile file,HttpServletRequest request){

        String result="";
        //文件保存目录路径
        String savePath = System.getProperty("hsx.webappRoot")+"attached/";

        //文件保存目录URL
        String saveUrl  = request.getContextPath() + "/attached/";

        //定义允许上传的文件扩展名
        HashMap<String, String> extMap = new HashMap<String, String>();
        extMap.put("image", "gif,jpg,jpeg,png,bmp");
        extMap.put("flash", "swf,flv");
        extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
        //最大文件大小
        long maxSize = 10000000;

//检查目录
        File uploadDir = new File(savePath);
        if(!uploadDir.isDirectory()){
            result=this.getError("上传目录不存在。");
        }
//检查目录写权限
        if(!uploadDir.canWrite()){

            result=this.getError("上传目录没有写权限。");
        }
        String dirName = request.getParameter("dir");
        if (dirName == null) {
            dirName = "image";
        }
        if(!extMap.containsKey(dirName)){
            result=this.getError("目录名不正确。");
        }
//创建文件夹
        savePath += dirName + "/";
        saveUrl += dirName + "/";
        File saveDirFile = new File(savePath);
        if (!saveDirFile.exists()) {
            saveDirFile.mkdirs();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String ymd = sdf.format(new Date());
        savePath += ymd + "/";
        saveUrl += ymd + "/";
        File dirFile = new File(savePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
        if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){

            result=this.getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。");
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;

        File tempFile = new File(savePath, newFileName);
        if (!tempFile.getParentFile().exists()) {
            tempFile.getParentFile().mkdirs();
        }
        if (!tempFile.exists()) {
            try {
                tempFile.createNewFile();
            }catch (IOException ex){
                result=this.getError("上传错误...");
            }

        }
        try{
            file.transferTo(tempFile);
        }catch (IOException ex){
            result=this.getError("上传错误...");
        }

        if(""==result){
            result=this.getSuccess(saveUrl + newFileName);
        }

        return result;
    }


    private String getSuccess(String url){
        ObjectMapper mapper = new ObjectMapper();
        Map obj = new HashMap();
        obj.put("error", 0);
        obj.put("url", url);
        String result="";
        try {
            result = mapper.writeValueAsString(obj);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    private String getError(String message) {
        ObjectMapper mapper = new ObjectMapper();
        Map obj = new HashMap();
        obj.put("error", 1);
        obj.put("message", message);
        String result="";
        try {
            result = mapper.writeValueAsString(obj);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}
